/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: CountChildHandler
 * Author:   zengjian
 * Date:     2018/9/20 21:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package netty.im;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 〈〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/20 21:02
 */
public class ServerHandler extends ChannelInitializer<SocketChannel> {

    private AtomicInteger count = new AtomicInteger(0);
    private Map<String, Channel> clientMap = new HashMap<>();

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1 << 7, Unpooled.wrappedBuffer(("\n").getBytes())));
        ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
        ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
        ch.pipeline().addLast(new SimpleChannelInboundHandler() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                String receiveMsg = (String) msg;
                System.out.println("IMServer接收到请求:\n" + receiveMsg);
                Channel channel = ctx.channel();
                if (receiveMsg.equalsIgnoreCase("GET")) {
                    String ips = String.join(",", clientMap.keySet());
                    channel.writeAndFlush("GET" + ";" + ips);
                }
                // MSG;ip:port;payload
                if (receiveMsg.startsWith("MSG")) {
                    String client = receiveMsg.split(";")[1];
                    Channel chanel = clientMap.get(client);
                    chanel.writeAndFlush(getIp(channel) + ":" + receiveMsg.split(";")[2].trim());
                }
                System.out.println("当前客户端连接数量：" + clientMap.size() + "当前连接：" + channel.toString());
            }

            @Override
            public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                clientMap.put(getIp(ctx.channel()), ctx.channel());
                System.out.println("当前客户端连接数量：" + clientMap.size() + ", 注册连接：" + ctx.channel().toString());
                super.channelRegistered(ctx);
            }

            @Override
            public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
                clientMap.remove(getIp(ctx.channel()), ctx.channel());
                System.out.println("当前客户端连接数量：" + clientMap.size() + ", 解注册连接：" + ctx.channel().toString());
                super.channelUnregistered(ctx);
            }

            String getIp(Channel channel) {
                InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
                return address.getHostName() + ":" + address.getPort();
            }
        });
    }
}